from pynput import keyboard


def on_press(key):
    try:
        # pynput.keyboard.Key
        # 字母和数字 key
        print('alphanumeric key {0} pressed'.format(key.char))
    except AttributeError:
        # 特殊的 key，例如：ctrl，backspace
        # pynput.keyboard.KeyCode
        print('special key {0} pressed'.format(key))


def on_release(key):
    print('{0} released'.format(key))
    print('key type {0}'.format(type(key)))
    if key == 's':
        # Stop listener
        listener.stop()

    if key == keyboard.Key.esc:
        # Stop listener
        return False


# Collect events until released
with keyboard.Listener(on_press=on_press,
                       on_release=on_release) as listener:
    listener.join()

# ...or, in a non-blocking fashion:
# listener = keyboard.Listener(
#     on_press=on_press,
#     on_release=on_release)
# listener.start()
